import Vue from 'vue';
import {ACCESS_TOKEN} from "../mutations-type"
import {userLogin, userLogout, getInfo} from "@/api/login";
import {removeTokenCookie, setCookie, removeToken} from "@/utils/auth";
import {message} from 'ant-design-vue';

const user = {
    state: {
        token: "",
        username: "",
        avatar: "",
        info: {
            id: '',
        },
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, userInfo) => {
            state.username = userInfo.username;
        },
        SET_INFO: (state, info) => {
            state.info = info;
            state.avatar = info.avatar;
        }
    },
    actions: {
        LOGIN({commit}, userInfo) {
            return new Promise((resolve, reject) => {
                userLogin(userInfo).then(result => {
                    if (result.success) {
                        message.success(result.message);
                        commit('SET_TOKEN', result.token);
                        resolve(result);
                    } else {
                        message.error(result.message);
                        reject(result)
                    }
                }).catch(error => {
                    reject(error)
                })
            });
        },
        LOGIN_INFO({commit}) {
            return new Promise((resolve, reject) => {
                getInfo().then(result => {
                    if (result.code === 200) {
                        commit('SET_INFO', result.record);
                        resolve(result);
                    } else {
                        message.error(result.message);
                        reject(result)
                    }
                }).catch(error => {
                    reject(error)
                })
            });
        },
        LOGOUT({commit}) {
            return new Promise((resolve, reject) => {
                userLogout().then(result => {
                    if (result.code === 200) {
                        // 清除vuex中的内容
                        commit('SET_NAME', {});
                        commit('SET_INFO', {});
                        commit('SET_TOKEN', "");
                        // 清除cookie中的用户token信息
                        removeTokenCookie();
                        resolve(result);
                    } else {
                        message.error(result.message);
                        reject(result)
                    }
                }).catch(() => {
                    resolve()
                })
            });
        },
    }
};

export default user;

